package com.br.nninn.expedia;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import com.br.nninn.bean.Search;
import com.br.nninn.util.Constants;

public class ExpediaSearch implements IExpediaSearch {
	
	
	@Override
	public JSONObject search(Search obj) {
		
		URL url;
		JSONObject jsonObj = null;
		try {
			url = new URL("http://api.ean.com/ean-services/rs/hotel/v3/list?minorRev=4&cid=55505&apiKey=y9ntyaaadceua98eshxkjpva" +
					"&customerIpAddress=192.168.1.100&locale=en_US&currencyCode=USD" +
					"&latitude=" + obj.getLatitude() + "&longitude=" + obj.getLongitude()  +
					"&searchRadius=" + Constants.searchRadius + "&searchRadiusUnit=MI&sort=PROXIMITY" +
					"&arrivalDate=&" + Constants.arrivalDate + "departureDate=" + Constants.departureDate +
					"&room1=2" +
					"&numberOfResults=" + Constants.numberOfResults
					);
			
			System.out.println(url.toString());
			
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.flush();
			
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			jsonObj = new JSONObject(rd.readLine());
			
		} catch (MalformedURLException e) {
			System.out.println("Error:" + e);	
		} catch (IOException e) {
			System.out.println("Error:" + e);
		} catch (JSONException e) {
			System.out.println("Error:" + e);
		} 
		
		return jsonObj;
	}

}
